# 请先安装必要的库: `pip3 install openai flask`

from flask import Flask, request, jsonify, render_template
from ai_service import AIService
import config
from tools import available_tools, get_tool_info, tool_functions, register_frontend_tool

# 创建Flask应用
app = Flask(__name__)

# 创建AI服务实例
ai_service = AIService(api_key=config.API_KEY, base_url=config.BASE_URL)

# 存储前端工具
frontend_tools = {}

@app.route('/chat', methods=['POST'])
def chat():
    """
    处理聊天请求的API端点
    """
    # 从请求中获取数据
    data = request.json
    user_message = data.get('message', '')
    
    # 检查是否有自定义工具集
    custom_tools = data.get('tools', None)
    
    # 使用AI服务处理消息
    response = ai_service.chat(user_message, custom_tools)
    
    # 返回处理结果
    return jsonify(response)

@app.route('/execute_tool', methods=['POST'])
def execute_tool():
    """
    直接执行工具的API端点
    """
    data = request.json
    tool_name = data.get('tool_name')
    parameters = data.get('parameters', {})
    
    # 检查是否是前端工具
    if tool_name.startswith('frontend_'):
        if tool_name in frontend_tools:
            # 返回前端工具调用请求，由前端执行
            return jsonify({
                "success": True,
                "is_frontend_tool": True,
                "tool_id": tool_name,
                "parameters": parameters
            })
        else:
            return jsonify({
                "success": False,
                "error": f"前端工具 '{tool_name}' 不存在"
            }), 404
    
    # 检查工具是否存在
    if tool_name not in tool_functions:
        return jsonify({
            "success": False,
            "error": f"工具 '{tool_name}' 不存在"
        }), 404
    
    try:
        # 执行工具函数
        result = tool_functions[tool_name](**parameters)
        return jsonify({
            "success": True,
            "result": result
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 400

@app.route('/register_frontend_tool', methods=['POST'])
def register_tool():
    """
    注册前端自定义工具
    """
    data = request.json
    tool_name = data.get('name')
    description = data.get('description', '')
    parameters = data.get('parameters', {})
    
    # 生成唯一ID
    tool_id = f"frontend_{tool_name}_{len(frontend_tools)}"
    
    # 保存工具定义
    frontend_tools[tool_id] = {
        "name": tool_name,
        "description": description,
        "parameters": parameters,
        "code": data.get('code', '')
    }
    
    # 向工具系统注册前端工具
    register_frontend_tool(tool_id, tool_name, description, parameters)
    
    return jsonify({
        "success": True,
        "tool_id": tool_id
    })

@app.route('/frontend_tools', methods=['GET'])
def get_frontend_tools():
    """
    获取所有前端工具
    """
    return jsonify({
        "frontend_tools": [
            {
                "id": tool_id,
                "name": tool_info["name"],
                "description": tool_info["description"],
                "parameters": tool_info["parameters"],
                "code": tool_info["code"]
            }
            for tool_id, tool_info in frontend_tools.items()
        ]
    })

@app.route('/tools', methods=['GET'])
def get_tools():
    """
    返回可用工具列表
    """
    return jsonify({
        "available_tools": get_tool_info()
    })

@app.route('/', methods=['GET'])
def index():
    """
    渲染聊天界面
    """
    return render_template('index.html')

if __name__ == '__main__':
    # 从配置文件读取服务器设置
    app.run(debug=config.DEBUG, host=config.HOST, port=config.PORT)